package cn.yangliu.config;

import cn.yangliu.constant.ResultCode;
import cn.yangliu.model.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * the type of serial-port-tool
 *
 * <p>
 * .
 *
 * @author 杨柳
 * @date 2024-05-29
 */
@Slf4j
@ControllerAdvice
public class ResponseResultAspect implements ResponseBodyAdvice<Object> {
    public ResponseResultAspect() {
        log.info("ResponseResultAspect init...");
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (Objects.isNull(requestAttributes)){
            throw new NullPointerException();
        }
        Object objBuffer = null;
        HttpServletResponse httpResponse = requestAttributes.getResponse();
        if (Objects.isNull(httpResponse)){
            throw new NullPointerException();
        }

        Result<Object> result = new Result<>(ResultCode.SUCCESS);
        result.setData(body);
        if (body instanceof String || selectedConverterType
                .isAssignableFrom(StringHttpMessageConverter.class)) {
            objBuffer = JSON.toJSONString(body);
        } else if (body instanceof Result) {
            objBuffer = body;
        } else {
            objBuffer = result;
        }
        return objBuffer;
    }
}
